package org.mbds.android.p2p.threads;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.mbds.android.p2p.services.P2pService;

import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pInfo;
import android.os.AsyncTask;
import android.widget.Toast;

public class SocketConnexion extends AsyncTask<WifiP2pInfo, String, Socket>{
	
	P2pService mService;
	ServerSocket mServerSocket;
	
	public SocketConnexion(P2pService service, ServerSocket ss){
		mService = service;
		mServerSocket = ss;
	}
	@SuppressLint("NewApi")
	@Override
	protected Socket doInBackground(WifiP2pInfo... params) {
		WifiP2pInfo info = params[0];
		Socket client = null;
		publishProgress("Ouverture de socket en cours....");
		if(info.isGroupOwner){
			try {
				client = mServerSocket.accept();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}else{
			client = new Socket();
			try {
				client.bind(null);
				client.connect(new InetSocketAddress(info.groupOwnerAddress.getHostAddress(), mServerSocket.getLocalPort()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return client;
	}
	
	@Override
	protected void onProgressUpdate(String...strings){
		Toast.makeText(mService.getApplicationContext(), strings[0], Toast.LENGTH_SHORT).show();
	}
	
	@Override
	protected void onPostExecute(Socket result){
		if(result != null)
			mService.addSocket(result);
	}

}
